// Copyright 2007-2009 Helsinki Institute for Information Technology
// and the authors.
//
// Authors: Konrad Markus <konrad.markus@hiit.fi>

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

function gP(o) {
    s = '[';
    for (p in o) {
        s += p + '->' + o[p] + ', ';
    }
    return s + ']';
}

var peerscape = function() {
    return {
        APPLICATION_IFRAME_ID: 'contentFrame',
        init: function() {
			if ($('body.content').length && !$('body.header').length) {
                peerscape.content.init();
            }
			if ($('body.admin').length && $('#connectionsTable').length) {
                peerscape.admin.init();
            }
			if ($('body.person').length) {
                peerscape.person.init();
            }
            peerscape.topLinks.init();
        },
        admin: {
            cTable: null,
            intervalId: null,
            interval: 2000, //ms
            init: function() {
                peerscape.admin.cTable = $('#connectionsTable');
                if ($('body.self').length) {
                    peerscape.admin.intervalId = setTimeout(peerscape.admin.updateConnections, peerscape.admin.interval);
                }
            },
            updateConnections: function() {
                $.ajax({
                    type: 'GET',
                    url: '/system/connections',
                    async: false,
                    success: function(data) {
                        data = eval(data);
                        peerscape.admin.cTable.find('th span').html(data.length);
                        // insert hidden rows
                        for (var d in data) {
                            peerscape.admin.cTable.find('tbody').append('<tr class="hidden"><td>'+data[d]+'</td></tr>');
                        }

                        // run through and unhide/delete to try and implement a kind of 'double buffering'
                        peerscape.admin.cTable.find('tbody tr').each(function() {
                            var tr = $(this);
                            if (tr.attr('class') == 'hidden') {
                                tr.attr('class', '');
                            }
                            else {
                                tr.remove();
                            }
                        });
                    },
                    error: null // ignore error
                });
                
                // start another cycle
                peerscape.admin.intervalId = setTimeout(peerscape.admin.updateConnections, peerscape.admin.interval);
            }
        },
        person: {
            cTarg: null,
            intervalId: null,
            interval: 5000, //ms
            init: function() {
                peerscape.person.cTarg = $('#subtitle a').eq(0);
                peerscape.person.intervalId = setTimeout(peerscape.person.updateConnections, peerscape.person.interval);
            },
            updateConnections: function() {
                $.ajax({
                    type: 'GET',
                    url: '/system/connections',
                    async: false,
                    success: function(data) {
                        data = eval(data);
                        peerscape.person.cTarg.html(data.length + (data.length == 1? ' peer connection' : ' peer connections'));
                    },
                    error: null // ignore error
                });
                
                // start another cycle
                peerscape.person.intervalId = setTimeout(peerscape.person.updateConnections, peerscape.person.interval);
            },

            _setOpenLink: function() {
                $('#info #expandLink a').eq(0)
                    .html('Show all...')
                    .unbind('click')
                    .bind('click', function() {
                        $('#info #personalInfo').slideDown('normal');
                        peerscape.person._setCloseLink();
                    });
            },
            _setCloseLink: function() {
                $('#info #expandLink a').eq(0)
                    .html('Hide')
                    .unbind('click')
                    .bind('click', function() {
                        $('#info #personalInfo').slideUp('fast');
                        peerscape.person._setOpenLink();
                    });
            }
        },
        application: {
            init: function() {
            }
        },
        content: {
            init: function() {
                $('#contentHolder').append('<iframe id="contentFrame" src="http://'+peerscape.contentInfo.iid+'.hexlabel.net/get/application/index.html" frameborder="0" marginheight="0"></iframe>');
                $('#contentFrame').load(function() {
                    peerscape.common.resize();
                });
            }
        },
        topLinks: {
            _menuTransitionFlags: {},
            _menuTransitionFlagsTickId: null,
            _menuTransitionFlagsTickDelayMS: 1000,

            init: function() {
                $('#topLinks ul li#peerscape').hoverIntent(
                    function() {
                        peerscape.topLinks.openMenu('peerscape');
                    },
                    function() {
                        peerscape.topLinks.closeMenu('peerscape');
                    }
                );
                peerscape.topLinks._menuTransitionFlagsTickId = setInterval(
                    function() {
                        for (var id in peerscape.topLinks._menuTransitionFlags) {
                            peerscape.topLinks._menuTransitionFlags[id] = false;
                        }
                    },
                    peerscape.topLinks._menuTransitionFlagsTickDelayMS
                );
            },
            openMenu: function(id) {
                if (! peerscape.topLinks._menuTransitionFlags[id]) {
                    $('#topLinks ul li#' + id + ' ul')
                        .slideDown('normal',
                            function() {
                                peerscape.topLinks._menuTransitionFlags[id] = false;
                            });
                    peerscape.topLinks._menuTransitionFlags[id] = true;
                }
            },
            closeMenu: function(id) {
                if (! peerscape.topLinks._menuTransitionFlags[id]) {
                    $('#topLinks ul li#' + id + ' ul')
                        .slideUp('fast',
                            function() {
                                peerscape.topLinks._menuTransitionFlags[id] = false;
                            });
                    peerscape.topLinks._menuTransitionFlags[id] = true;
                }
            }
        },
        common: {
            escapeHTML: function(s) {
                if (!s) {
                    return s;
                }
                return s.replace(/&/g,'&amp;').
                    replace(/>/g,'&gt;').
                    replace(/</g,'&lt;');
            },
            unescapeHTML: function(s) {
                if (!s) {
                    return s;
                }
                return s.replace(/&amp;/g,'&').
                    replace(/&gt;/g,'>').
                    replace(/&lt;/g,'<');
            },
            /* resize content iframe to fit to its content */
            resize: function() {
                var id = peerscape.APPLICATION_IFRAME_ID;
                var iframe = document.getElementById(id);

                if (!iframe) {
                    return;
                }

                if ($.browser.msie) {
                    oBody = iframe.document.body;
                    iframe.style.height = oBody.scrollHeight + (oBody.offsetHeight - oBody.clientHeight);
                }
                else {
                    var iframeDocA = $(iframe).contents()[0];
                    var iframeDocB = $(iframe).contents().children()[0];

                    /* hack for differences in safari */
                    if (iframeDocA.height > iframeDocB.scrollHeight) {
                        iframe.height = iframeDocA.height;
                    }
                    else {
                        iframe.height = iframeDocB.scrollHeight;
                    }
                }

                if (!iframe.contentWindow.onresize) {
                    iframe.contentWindow.onresize = function() {
                        peerscape.common.resize(); 
                    }
                }
                //console.log('r: ' + iframe.height);
                return;
            },

            /* resize given element to fit within parent height */
            resizeToFit: function(id) {
				var iframe = $("#" + id);
				if (iframe) {
                    var h = $(document).height();
                    //console.log('RESIZE: ' + h);
                    h -= iframe.offset().top;
                    h -= 37;
					iframe.height(h);
                    window.onresize = function() { peerscape.common.resizeToFit(id); }
                }
            },

            /* move scrolling to the top of the whole thing */
            scrollToTop: function() {
                window.scroll(0, 0);
            }
        }
    }
}();

$(function() { peerscape.init(); });
